import socket
import asyncio
import logging
logger = logging.getLogger(__name__)

Conn = socket.socket
BUFFER_SIZE = 1024


class Sock(object):
    """
    Sock
    """
    def __init__(self):
        self.loop = asyncio.get_event_loop()

    async def read(self, conn: Conn):
        data = await self.loop.sock_recv(conn, BUFFER_SIZE)
        return data



class Local(object):
    """
    Local
    """
    def __init__(self, listen_addr):
        self.loop = asyncio.get_event_loop()
        self.listen_addr = listen_addr

    async def listen(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
            listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            listener.bind(self.listen_addr)
            listener.listen(socket.SOMAXCONN)
            listener.setblocking(False)

            while True:
                connection, address = await self.loop.sock_accept(listener)
                logger.info('Receive %s:%d', *address)
                asyncio.ensure_future(self.handle_conn(connection))

    async def handle_conn(conn: Conn):
        pass
